#include <SDL/SDL.h>

#include "mouse.h"

Mouse::Mouse():m_actualPosX(0),m_actualPosY(0),m_oldPosX(0),m_oldPosY(0)
{
  memset(m_actualButtons,0,sizeof(bool)*MOUSEBUTTONS);
  memset(m_oldButtons,0,sizeof(bool)*MOUSEBUTTONS);
}

Mouse::~Mouse()
{
}

void Mouse::update()
{
  memcpy(m_actualButtons,m_oldButtons,sizeof(bool)*MOUSEBUTTONS);
  m_actualPosX = m_oldPosX;
  m_actualPosY = m_oldPosY;
}

void Mouse::receiveEvent(const SDL_Event &sdl_event)
{
  if(sdl_event.type==SDL_MOUSEBUTTONDOWN || sdl_event.type==SDL_MOUSEBUTTONUP)
  {
    m_actualButtons[sdl_event.button.button]=(sdl_event.button.state==SDL_PRESSED);
  }
  else if(sdl_event.type==SDL_MOUSEMOTION)
  {
    m_actualPosX = sdl_event.motion.x;
    m_actualPosY = sdl_event.motion.y;
  }
}

bool Mouse::isEventTriggered(const Event &event,Sint32 &magnitude)
{
  if(event.peripheral!=Event::MOUSE)
    return false;
  
  if(event.component>COMP_MOUSE_Y || event.component<0)
    return false;
 
  if(event.component==COMP_MOUSE_X)
  {
    switch(event.action)
    {
      case Event::ON_PRESS:
      case Event::ON_PRESSING:
        if(m_actualPosX && !m_oldPosX)
        {
          magnitude=m_actualPosX;
          return true;
        }
        break;
        
      default:
          return false;
    }
  }
  else if(event.component==COMP_MOUSE_Y)
  {
    switch(event.action)
    {
      case Event::ON_PRESS:
      case Event::ON_PRESSING:
        if (m_actualPosY && !m_oldPosY)
        {
          magnitude=m_actualPosY;
          return true;
        }
        break;
        
      default:
          return false;
    }
  }
  else   //Botones
  {
    switch(event.action)
    {
      case Event::ON_PRESS:
        if((m_actualButtons[event.component] && !m_oldButtons[event.component]))
        {
          magnitude=1;
          return true;
        }
        break;
      
      case Event::ON_PRESSING:
        if(m_actualButtons[event.component])
        {
          magnitude=1;
          return true;
        }
        break;
        
      case Event::ON_RELEASE:
        if((m_oldButtons[event.component] && !m_actualButtons[event.component]))
        {
          magnitude=1;
          return true;
        }
        break;
        
      case Event::ON_RELEASING:
        if(!m_actualButtons[event.component])
        {
          magnitude=1;
          return true;
        }
        break;
    }
  }

  return false;
}
